package com.tansty.web.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tansty.dao.mapper.UserMapper;
import com.tansty.pojo.po.Role;
import com.tansty.pojo.po.User;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * description: 用户认证 <br>
 * date: 2021/8/1 15:14 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MyPasswordEncoder passwordEncoder ;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) {
        // 根据用户名去数据库中查询
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", username).ne("deleted",1));
        if(user==null){
            return null;
            //throw new UsernameNotFoundException("无此用户名");
            //throw new InternalAuthenticationServiceException("用户名不存在!");
        }else {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            // 数据库中查询出所拥有的角色进行赋予
            for (Role role : userMapper.findRoleByUsername(username)) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            return new JwtUser(user,authorities);
        }
    }

}
